import MarkdownIt from 'markdown-it';
import attrs from 'markdown-it-attrs';

// 创建markdown-it实例，配置完整的markdown支持
const md = new MarkdownIt({
  html: true,          // 启用HTML标签支持
  breaks: true,        // 转换换行符为<br>
  linkify: true,       // 自动转换URL为链接
  typographer: true,   // 启用一些语言中性的替换 + 引号美化
})
  .use(attrs)          // 支持属性语法
  .enable(['table']); // 启用表格和删除线支持

// 自定义表格渲染，添加样式
md.renderer.rules.table_open = function (_tokens, _idx, _options, _env, _slf) {
  return '<div class="overflow-x-auto my-4"><table class="min-w-full divide-y divide-gray-200 border border-gray-300">\n';
};

md.renderer.rules.table_close = function (_tokens, _idx, _options, _env, _slf) {
  return '</table></div>\n';
};

md.renderer.rules.thead_open = function (_tokens, _idx, _options, _env, _slf) {
  return '<thead class="bg-gray-50">\n';
};

md.renderer.rules.tbody_open = function (_tokens, _idx, _options, _env, _slf) {
  return '<tbody class="bg-white divide-y divide-gray-200">\n';
};

md.renderer.rules.tr_open = function (_tokens, _idx, _options, _env, _slf) {
  return '<tr>\n';
};

md.renderer.rules.th_open = function (_tokens, _idx, _options, _env, _slf) {
  return '<th class="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider border-r border-gray-300">';
};

md.renderer.rules.td_open = function (_tokens, _idx, _options, _env, _slf) {
  return '<td class="px-3 py-2 whitespace-nowrap text-sm text-gray-900 border-r border-gray-300">';
};

// 自定义标题渲染，添加样式
md.renderer.rules.heading_open = function (tokens, idx, _options, _env, _slf) {
  const token = tokens[idx];
  const level = token.markup.length; // 获取标题级别
  
  const classes = {
    1: 'text-2xl font-bold text-gray-900 mt-6 mb-4',
    2: 'text-xl font-bold text-gray-900 mt-5 mb-3',
    3: 'text-lg font-semibold text-gray-800 mt-4 mb-2',
    4: 'text-base font-semibold text-gray-800 mt-3 mb-2',
    5: 'text-sm font-semibold text-gray-700 mt-2 mb-1',
    6: 'text-xs font-semibold text-gray-700 mt-2 mb-1'
  };
  
  return `<h${level} class="${classes[level as keyof typeof classes] || classes[3]}">`;
};

// 自定义代码块渲染
md.renderer.rules.fence = function (tokens, idx, _options, _env, _slf) {
  const token = tokens[idx];
  const info = token.info ? md.utils.unescapeAll(token.info).trim() : '';
  const langName = info ? info.split(/\s+/g)[0] : '';
  
  if (langName) {
    return `<pre class="bg-gray-100 rounded-md p-4 overflow-x-auto my-3"><code class="language-${langName} text-sm">${md.utils.escapeHtml(token.content)}</code></pre>\n`;
  }
  
  return `<pre class="bg-gray-100 rounded-md p-4 overflow-x-auto my-3"><code class="text-sm">${md.utils.escapeHtml(token.content)}</code></pre>\n`;
};

// 自定义列表样式 - 更紧凑的显示
md.renderer.rules.bullet_list_open = function (_tokens, _idx, _options, _env, _slf) {
  return '<ul class="list-disc list-inside space-y-1 my-2 ml-4">\n';
};

md.renderer.rules.ordered_list_open = function (tokens, idx, _options, _env, _slf) {
  // 获取有序列表的起始编号
  const start = tokens[idx].attrGet('start') || 1;
  return `<ol start="${start}" class="list-decimal list-outside space-y-1 my-2 ml-4">\n`;
};

md.renderer.rules.list_item_open = function (_tokens, _idx, _options, _env, _slf) {
  return '<li class="leading-relaxed">';
};

// 自定义段落样式 - 在列表项中不添加额外的margin
md.renderer.rules.paragraph_open = function (tokens, idx, _options, _env, _slf) {
  // 检查是否在列表项中
  let inListItem = false;
  for (let i = idx - 1; i >= 0; i--) {
    if (tokens[i].type === 'list_item_open') {
      inListItem = true;
      break;
    }
    if (tokens[i].type === 'list_item_close') {
      break;
    }
  }
  
  // 如果在列表项中，使用更紧凑的样式
  if (inListItem) {
    return '<span class="leading-relaxed">';
  }
  
  return '<p class="mb-2 leading-relaxed">';
};

md.renderer.rules.paragraph_close = function (tokens, idx, _options, _env, _slf) {
  // 检查是否在列表项中
  let inListItem = false;
  for (let i = idx - 1; i >= 0; i--) {
    if (tokens[i].type === 'list_item_open') {
      inListItem = true;
      break;
    }
    if (tokens[i].type === 'list_item_close') {
      break;
    }
  }
  
  // 如果在列表项中，使用span标签
  if (inListItem) {
    return '</span>';
  }
  
  return '</p>';
};

// 处理HTML块级标签（包括自定义标签）
md.renderer.rules.html_block = function (tokens, idx, _options, _env, _slf) {
  const token = tokens[idx];
  const content = token.content;
  
  // 处理自定义标签
  const processedContent = content
    .replace(/<highlight>/g, '<div class="bg-blue-50 border-l-4 border-blue-400 p-3 my-2 rounded-r">')
    .replace(/<\/highlight>/g, '</div>')
    .replace(/<rise>/g, '<span class="text-blue-600 font-bold">')
    .replace(/<\/rise>/g, '</span>');
  
  return processedContent;
};

// 处理HTML内联标签
md.renderer.rules.html_inline = function (tokens, idx, _options, _env, _slf) {
  const token = tokens[idx];
  const content = token.content;
  
  // 处理内联自定义标签
  const processedContent = content
    .replace(/<highlight>/g, '<div class="bg-blue-50 border-l-4 border-blue-400 p-3 my-2 rounded-r">')
    .replace(/<\/highlight>/g, '</div>')
    .replace(/<rise>/g, '<span class="text-blue-600 font-bold">')
    .replace(/<\/rise>/g, '</span>');
  
  return processedContent;
};

// 预处理文本，确保自定义标签被正确识别
const preprocessText = (text: string): string => {
  // 确保自定义标签前后有适当的空白，以便markdown-it正确解析
  return text
    .replace(/(<highlight>)/g, '\n$1')
    .replace(/(<\/highlight>)/g, '$1\n')
    .replace(/(<rise>)/g, ' $1')
    .replace(/(<\/rise>)/g, '$1 ')
    // 清理多余的空白，但保留必要的换行
    .replace(/[ \t]+/g, ' ')
    .replace(/\n\s*\n\s*\n/g, '\n\n')
    .trim();
};

// 流式安全渲染函数 - 使用占位符策略
export const renderMarkdownStreaming = (text: string, _buttonType: 'send' | 'buy' | 'none' = 'send'): string => {
  try {
    if (!text || text.trim() === '') {
      return '<div style="color: #9ca3af; font-style: italic;">开始接收数据...</div>';
    }

    // 第一步：用占位符替换可能不完整的特殊标签
    let processedText = text;
    
    // 替换新的趋势图卡片标签格式 [CARD:基金名称-时间范围-累计收益率走势]
    processedText = processedText.replace(/\[CARD:([^\]]+)\]/g, (_match, cardContent) => {
      return `<div style="
        display: inline-flex; 
        align-items: center; 
        gap: 6px; 
        background: #ecfdf5; 
        border: 1px solid #a7f3d0; 
        border-radius: 6px; 
        padding: 4px 8px; 
        margin: 2px;
        font-size: 12px;
        color: #065f46;
      ">
        <span style="animation: spin 1s linear infinite;">📈</span>
        <span>${cardContent}</span>
      </div>`;
    });
    
    // 替换完整的DIVIDER标签为占位符
    processedText = processedText.replace(/\[DIVIDER\]/g, () => {
      return `<div style="
        display: flex; 
        align-items: center; 
        gap: 8px; 
        margin: 8px 0;
        padding: 6px 12px;
        background: #fef3c7;
        border: 1px solid #fbbf24;
        border-radius: 6px;
        font-size: 12px;
        color: #92400e;
      ">
        <span>📋</span>
        <span>内容分段</span>
      </div>`;
    });
    
    // 处理不完整的标签 - 显示为正在输入状态
    const hasIncompleteTrendCard = (processedText.includes('[CARD') && !processedText.match(/\[CARD:[^\]]*\]/));
    const hasIncompleteDivider = processedText.includes('[DIVIDER') && !processedText.includes('[DIVIDER]');

    if ( hasIncompleteTrendCard || hasIncompleteDivider) {
      // 找到最后一个不完整标签的位置
      let safeEndIndex = processedText.length;  
      
      // 检查不完整的趋势图卡片标签
      const lastIncompleteTC = processedText.lastIndexOf('[CARD');
      if (lastIncompleteTC !== -1) {
        const afterTC = processedText.substring(lastIncompleteTC);
        if (!afterTC.includes(']')) {
          safeEndIndex = Math.min(safeEndIndex, lastIncompleteTC);
        }
      }
      
      // 检查不完整的分隔符标签
      const lastIncompleteDIV = processedText.lastIndexOf('[DIVIDER');
      if (lastIncompleteDIV !== -1) {
        const afterDIV = processedText.substring(lastIncompleteDIV);
        if (!afterDIV.includes(']')) {
          safeEndIndex = Math.min(safeEndIndex, lastIncompleteDIV);
        }
      }
      
      // 分离安全和不安全部分
      const safeText = processedText.substring(0, safeEndIndex);
      const unsafeText = processedText.substring(safeEndIndex);
      
      // 渲染安全部分
      const safeHtml = safeText ? preprocessAndRender(safeText) : '';
      
      // 不安全部分显示为正在输入状态
      const unsafeHtml = unsafeText ? `
        <span style="
          color: #6b7280; 
          background: #f9fafb;
          padding: 2px 6px;
          border-radius: 4px;
          font-style: italic;
        ">
          ${unsafeText}<span style="animation: blink 1s infinite; margin-left: 2px;">|</span>
        </span>
      ` : '';
      
      return safeHtml + unsafeHtml;
    }
    
    // 没有不完整标签，直接渲染
    return preprocessAndRender(processedText);
    
  } catch (error) {
    console.warn('流式渲染出错，降级到安全模式:', error);
    // 如果渲染出错，至少显示文本内容
    return `<div style="color: #374151; white-space: pre-wrap;">${text}</div>`;
  }
};

// 辅助函数：预处理并渲染markdown
const preprocessAndRender = (text: string): string => {
  try {
    const processedText = preprocessText(text);
    let html = md.render(processedText);
    
    // 后处理：替换自定义标签
    html = html
      .replace(/<highlight>/g, '<div class="bg-blue-50 border-l-4 border-blue-400 p-3 my-2 rounded-r">')
      .replace(/<\/highlight>/g, '</div>')
      .replace(/<rise>/g, '<span class="text-blue-600 font-bold">')
      .replace(/<\/rise>/g, '</span>');
    
    return html;
  } catch (error) {
    console.warn('markdown渲染出错:', error);
    return `<div style="color: #374151; white-space: pre-wrap;">${text}</div>`;
  }
};

// 添加CSS动画样式
const addTrendCardStyles = () => {
  if (document.getElementById('trendcard-styles')) return;
  
  const style = document.createElement('style');
  style.id = 'trendcard-styles';
  style.textContent = `
    @keyframes spin {
      0% { transform: rotate(0deg); }
      100% { transform: rotate(360deg); }
    }
  `;
  document.head.appendChild(style);
};

// 在模块加载时添加样式
if (typeof document !== 'undefined') {
  addTrendCardStyles();
}

// 导出markdown-it实例供高级用法
export { md };

export default renderMarkdownStreaming;